package com.favccxx.message.domain.message.adapter.amqp;

import com.favccxx.message.domain.message.MessageProtocol;
import com.favccxx.message.domain.message.adapter.CamelAdapter;
import com.favccxx.message.domain.message.entity.endpoint.AmqpEndPoint;
import com.favccxx.message.domain.message.entity.endpoint.MessageEndPoint;
import lombok.extern.slf4j.Slf4j;
import org.apache.camel.CamelContext;
import org.apache.camel.component.amqp.AMQPComponent;
import org.apache.qpid.jms.JmsConnectionFactory;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class AmqpAdapter implements CamelAdapter {

    @Override
    public String getUri(CamelContext camelContext, MessageEndPoint endPoint) {
        if (endPoint instanceof AmqpEndPoint) {
            AmqpEndPoint amqpEndPoint = (AmqpEndPoint) endPoint;
            AMQPComponent component = new AMQPComponent();
            component.setConnectionFactory(createJMSConnection(endPoint));
            // create url
            String destinationType = "queue";
            if (amqpEndPoint.isDuribility()) {
                destinationType = "topic";
                component.setSubscriptionDurable(true);
                // if want to get message from last consumer position, clientId need to store.
                component.setClientId(String.valueOf(System.currentTimeMillis()));
            }
            camelContext.addComponent(amqpEndPoint.getCode(), component);
            String uri = amqpEndPoint.getCode() + ":" + destinationType + ":" + amqpEndPoint.getQueueName();
            log.info("-------------------------message from uri: " + uri);
            return uri;

        }
        return "";
    }


    private JmsConnectionFactory createJMSConnection(MessageEndPoint message) {
        JmsConnectionFactory connectionFactory = new JmsConnectionFactory();
        String url = "amqp://" + message.getUrl() + ":" + message.getPort();
        connectionFactory.setRemoteURI(url);
        connectionFactory.setUsername(message.getUsername());
        connectionFactory.setPassword(message.getPassword());
        return connectionFactory;
    }


    @Override
    public String getDriverType() {
        return MessageProtocol.AMQP.getName();
    }
}
